package com.zlt.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

//生成验证码的工具类
public class VerifyCode {

    private static final int WIDTH = 160;
    private static final int HEIGHT = 30;

    private String verifyCode;

    /**
     * 获取验证码
     *
     * @return
     */
    public String getVerifyCode() {
        return verifyCode;
    }

    public VerifyCode() {
    }

    /**
     * 生成验证码图片
     *
     * @return BufferedImage
     */
    public BufferedImage verifyImage() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        setBackGroundColor(graphics);
        drawRandomLine(graphics);
        drawRandomChar(graphics);
        graphics.dispose();
        return image;
    }

    /**
     * 设置背景色
     *
     * @param graphics
     */
    private void setBackGroundColor(Graphics2D graphics) {
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
    }

    /**
     * 生成随机线条
     *
     * @param graphics
     */
    private void drawRandomLine(Graphics2D graphics) {
        graphics.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
        for (int i = 1; i <= 10; i++) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            graphics.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 生成随机字符
     *
     * @param graphics
     */
    private void drawRandomChar(Graphics2D graphics) {
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        String base = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int x = 10;
        StringBuilder string = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            String ch = base.charAt(new Random().nextInt(base.length())) + "";
            string.append(ch);
            int degree = new Random().nextInt() % 40;
            graphics.rotate(degree * Math.PI / 180, x, 30);
            graphics.drawString(ch, x, 20);
            graphics.rotate(-degree * Math.PI / 180, x, 30);
            x += 30;
        }
        verifyCode = string.toString();
    }

}
